//*********************************************************
//
//    Copyright (c) Microsoft. All rights reserved.
//    This code is licensed under the Apache License, Version 2.0.
//    THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
//    ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
//    IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
//    PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
//
//*********************************************************

namespace Microsoft.Research.ScientificWorkflow.UIDesigner.ActivityImportWizards
{
    using System;
    using System.IO;
    using System.Windows;
    using Microsoft.Research.ScientificWorkflow.TridentModel;
    using Microsoft.Research.ScientificWorkflow.TridentUtilities;
    using Microsoft.Research.DataLayer;
    using System.Collections.ObjectModel;
    using System.Globalization;

    /// <summary>
    /// 
    /// </summary>
    public partial class WSImportSummary : IActivityWizardScreens
    {
        WSWizardPresenter WSPresenter;

        public WSImportSummary(WSWizardPresenter presenter)
        {
            this.InitializeComponent();
            this.WSPresenter = presenter;
            this.DataContext = presenter.WSModel;

            // After generation of activity assembly, this is UI result.
            if (File.Exists(WebServiceWizardModel.ActivityTempPath))
            {
                this.failureStackPanel.Visibility = Visibility.Hidden;
                this.successStackPanel.Visibility = Visibility.Visible;
                this.importButton.IsEnabled = true;
            }
            else
            {
                this.successStackPanel.Visibility = Visibility.Hidden;
                this.failureStackPanel.Visibility = Visibility.Visible;
                this.importButton.IsEnabled = false;
            }

            // Make the import result section hidden.
            this.importResult.Visibility = Visibility.Hidden;
            this.otherOptions.IsEnabled = !this.importButton.IsEnabled;
        }

        /// <summary>
        /// Called when [click next].
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The <see cref="System.Windows.RoutedEventArgs"/> instance containing the event data.</param>
        private void OnClickNext(object sender, RoutedEventArgs e)
        {
            if (null != NextButtonEventHandler)
            {
                NextButtonEventHandler(sender, null);
            }
        }

        /// <summary>
        /// Called when [click back].
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The <see cref="System.Windows.RoutedEventArgs"/> instance containing the event data.</param>
        private void OnClickBack(object sender, RoutedEventArgs e)
        {
            if (null != BackButtonEventHandler)
            {
                // No Back.
            }
        }

        /// <summary>
        /// Called when [click finished].
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The <see cref="System.Windows.RoutedEventArgs"/> instance containing the event data.</param>
        private void OnClickCancel(object sender, RoutedEventArgs e)
        {
            CancelButtonEventHandler(sender, e);
        }

        /// <summary>
        /// Called when [import activity].
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The <see cref="System.Windows.RoutedEventArgs"/> instance containing the event data.</param>
        private void OnImportActivity(object sender, RoutedEventArgs e)
        {
            try
            {
                // Get the current cursor and show it busy.
                System.Windows.Input.Cursor currentCursor = this.Cursor;
                this.Cursor = System.Windows.Input.Cursors.Wait;

                // Get the activity assembly file name to import.
                string activityAssemblyPath =
                    (WSPresenter.WSModel.IsCopyActivityCodeEnabled &&
                    !string.IsNullOrEmpty(WSPresenter.WSModel.OutputBinariesPath)) ?
                    Path.Combine(WSPresenter.WSModel.OutputBinariesPath, Path.GetFileName(WebServiceWizardModel.ActivityTempPath)) :
                    WebServiceWizardModel.ActivityTempPath;

                string activityFullName = string.Format(CultureInfo.InvariantCulture, "{0}.{1}", WebServiceWizardModel.ActivityNamespace, WSPresenter.WSModel.ActivityName);
                Activity regActivity = Activity.CommonSearches.FindActivityInRegistry(activityFullName, WSPresenter.RegistryHandle);
                bool continueWithImport = true;
                if (regActivity != null)
                {
                    if (MessageBoxResult.No ==
                        TridentMessageBox.ShowTridentConfirmationYesNoMessageBox(
                        TridentResourceManager.GetString("WebServiceActivityAlreadyExists")))
                    {
                        continueWithImport = false;
                    }
                }

                if (continueWithImport)
                {
                    // Import the Activity.
                    UIHelper helper = new UIHelper(WSPresenter.RegistryHandle);

                    Collection<FileReference> references = new Collection<FileReference>();
                    Helper.BuildReferences(references, activityAssemblyPath, Path.GetDirectoryName(activityAssemblyPath));

                    WSPresenter.WSModel.IsImportSuccessful = helper.ImportActivities(references, true);
                    if (WSPresenter.WSModel.IsImportSuccessful)
                    {
                        // Make the import result area Visible.
                        this.importResult.Visibility = Visibility.Visible;
                        this.importButton.IsEnabled = false;

                        // Show result on UI.
                        this.importSuccessMessage.Visibility = Visibility.Visible;
                        this.importFailMessage.Visibility = Visibility.Hidden;

                        try
                        {
                            Activity activity = Activity.CommonSearches.FindActivityInRegistry(activityFullName, WSPresenter.RegistryHandle);

                            // After Import, update the icon path.
                            if (null != WSPresenter.RegistryHandle && !string.IsNullOrEmpty(WSPresenter.WSModel.ActivityImageSource))
                            {
                                System.Drawing.Image img = System.Drawing.Image.FromFile(WSPresenter.WSModel.ActivityImageSource);
                                if (img != null)
                                {
                                    try
                                    {
                                        WSPresenter.RegistryHandle.AutoSave = true;
                                        img.Tag = System.IO.Path.GetFileName(WSPresenter.WSModel.ActivityImageSource);
                                        activity.Icon = img;
                                    }
                                    finally
                                    {
                                        WSPresenter.RegistryHandle.AutoSave = false;
                                    }
                                }
                            }

                            // Update source of this activity
                            activity.Source = WSPresenter.WSModel.WebServiceUrl.ToString();
                            activity.Save();
                        }
                        catch (Exception exp)
                        {
                            TridentMessageBox.ShowTridentErrorMessageBox(exp.Message);
                        }
                    }
                    else
                    {
                        OnImportFailure();
                    }
                }
                this.otherOptions.IsEnabled = !this.importButton.IsEnabled || !continueWithImport;

                // Restore the cursor.
                this.Cursor = currentCursor;
            }
            catch (Exception exp)
            {
                TridentMessageBox.ShowTridentErrorMessageBox(exp.Message);
            }
        }

        /// <summary>
        /// Called when [import failure].
        /// </summary>
        private void OnImportFailure()
        {
            // Make the import result area Visible.
            this.importResult.Visibility = Visibility.Visible;
            this.importButton.IsEnabled = false;

            // Show result on UI.
            this.importSuccessMessage.Visibility = Visibility.Hidden;
            this.importFailMessage.Visibility = Visibility.Visible;
        }

        #region IActivityWizardScreens Members

        /// <summary>
        /// Occurs when [Next button handler].
        /// </summary>
        public event EventHandler<ActivityImportEventArgs> NextButtonEventHandler;

        /// <summary>
        /// Occurs when [Back button handler].
        /// </summary>
        public event EventHandler BackButtonEventHandler;

        /// <summary>
        /// Occurs when [Cancel button handler].
        /// </summary>
        public event EventHandler CancelButtonEventHandler;

        /// <summary>
        /// Handles move request.
        /// </summary>
        public event EventHandler OnWindowMoveEventHandler;

        #endregion
        
        /// <summary>
        /// Called when mouse left button down.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The <see cref="System.Windows.Input.MouseButtonEventArgs"/> instance containing the event data.</param>
        private void OnMouseLeftButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            if (this.OnWindowMoveEventHandler != null)
            {
                this.OnWindowMoveEventHandler(sender, e);
            }
        }
    }
}